/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package company.beans;

import facades.CompanyEconomicTypeFacade;
import facades.CompanyFacade;
import facades.CompanySectorFacade;
import facades.CompanyTypeFacade;
import facades.UserFacade;
import facades.UserTypeFacade;
import entities.Company;
import entities.User;
import util.ImageStoreHelper;
import util.Sha256Encrypter;
import java.io.File;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.event.Event;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.transaction.Transactional;
import mail.EmailEJB;
import mail.EmailTemplateHelper;
import mail.datamodel.IdDataSource;
import org.primefaces.context.RequestContext;
import qualifiers.CreatedEntityEvent;

/**
 *
 * @author damfercer
 */
@Named(value = "createCompanyBean")
@SessionScoped
public class CreateCompanyBean implements Serializable {
    @Inject
    @CreatedEntityEvent
    private Event<User> createdUserEvent;
    @Inject
    private UserTypeFacade userTypeEJB;
    @Inject
    private UserFacade userEJB;
    @Inject
    private CompanyTypeFacade companyTypeEJB;
    @Inject
    private CompanyEconomicTypeFacade companyEconomicTypeEJB;
    private Company company;
    private String companyName;
    private String companyCif;
    private String companyEmail;
    private String companyContact;
    @Inject
    private EmailEJB emailEJB;
    
    @Inject
    @CreatedEntityEvent
    private Event<Company> newCompanyEvent;
    /**
     * Creates a new instance of CreateCompanyBean
     */
    public CreateCompanyBean() {
        company=new Company();
        company.setAvailableCredits(0);
        company.setIdUser(new User());
    }
    
    public void sendCompanyData(){
        String subject="[REGISTRO-EMPRESA-WEBSITE]";
        String html=EmailTemplateHelper.getHtmlDivText("Email: "+companyEmail)+EmailTemplateHelper.getHtmlDivText("Nombre Compañía: "+companyName)+EmailTemplateHelper.getHtmlDivText("Persona de Contacto: "+companyContact)+EmailTemplateHelper.getHtmlDivText("Cif de la compañía: "+companyCif);
        List<IdDataSource> dataSources=new ArrayList<IdDataSource>();
        emailEJB.sendHtmlMail("suggestions@therecruitery.com", subject, html, dataSources);
        resetFields();
        RequestContext requestContext=RequestContext.getCurrentInstance();
        requestContext.execute("registerDialog.hide();");
        requestContext.execute("registerDialogOK.show();");
    }
    
    public void sendCompanyDataSmarphone(){
        String subject="[REGISTRO-EMPRESA-WEBSITE]";
        String html=EmailTemplateHelper.getHtmlDivText("Email: "+companyEmail)+EmailTemplateHelper.getHtmlDivText("Nombre Compañía: "+companyName)+EmailTemplateHelper.getHtmlDivText("Persona de Contacto: "+companyContact)+EmailTemplateHelper.getHtmlDivText("Cif de la compañía: "+companyCif);
        List<IdDataSource> dataSources=new ArrayList<IdDataSource>();
        emailEJB.sendHtmlMail("suggestions@therecruitery.com", subject, html, dataSources);
        resetFields();
        FacesContext context=FacesContext.getCurrentInstance();
        ResourceBundle rb=ResourceBundle.getBundle("messages");
        String recoverSent=rb.getString("CompanyDataSend");
        FacesMessage message =new FacesMessage(recoverSent, recoverSent);
        message.setSeverity(FacesMessage.SEVERITY_INFO);
        context.addMessage(null, message); 
        context.renderResponse();
    }
    
    public void resetFields(){
        companyName="";
        companyCif="";
        companyEmail="";
        companyContact="";
    }
    
    @Transactional
    public String createCompany(){
        Date date = new Date();
        User user=company.getIdUser();
        user.setCompany(company);
        user.setActive(true);
        user.setCreationDate(date);
        user.setLastDate(date);
        user.setLogins(0);
        user.setUserType(userTypeEJB.find(2));
        user.getCompany().setCompanyType(companyTypeEJB.find(1));
        user.getCompany().setCompanyEconomicType(companyEconomicTypeEJB.find(1));
        user.setEmail(user.getEmail().toLowerCase());
        try {
            user.setPassword(Sha256Encrypter.getSha256(user.getPassword()));
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CreateCompanyBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(CreateCompanyBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        userEJB.create(user);
        createdUserEvent.fire(user);
        makeDirs();
        newCompanyEvent.fire(user.getCompany());
        return "/views/company/NewEditCompanyView?faces-redirect=true";
    }
    
    public void makeDirs(){
        File imagesDir=new File(ImageStoreHelper.pathToCompanyPersistentStore+"/"+getCompany().getIdCompany().toString()+"/"+"images");
        File videosDir=new File(ImageStoreHelper.pathToCompanyPersistentStore+"/"+getCompany().getIdCompany().toString()+"/"+"videos");
        imagesDir.mkdirs();
        videosDir.mkdirs();
    }

    
    public Company getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(Company company) {
        this.company = company;
    }

    /**
     * @return the companyName
     */
    public String getCompanyName() {
        return companyName;
    }

    /**
     * @param companyName the companyName to set
     */
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    /**
     * @return the companyCif
     */
    public String getCompanyCif() {
        return companyCif;
    }

    /**
     * @param companyCif the companyCif to set
     */
    public void setCompanyCif(String companyCif) {
        this.companyCif = companyCif;
    }

    /**
     * @return the companyEmail
     */
    public String getCompanyEmail() {
        return companyEmail;
    }

    /**
     * @param companyEmail the companyEmail to set
     */
    public void setCompanyEmail(String companyEmail) {
        this.companyEmail = companyEmail;
    }

    /**
     * @return the companyContact
     */
    public String getCompanyContact() {
        return companyContact;
    }

    /**
     * @param companyContact the companyContact to set
     */
    public void setCompanyContact(String companyContact) {
        this.companyContact = companyContact;
    }

}
